package www.yingdi365.com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;

import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseActivity;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.model.AppECard;
import www.yingdi365.com.model.AppECardPaging;
import www.yingdi365.com.model.OkObject;
import www.yingdi365.com.util.DpUtils;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.viewholder.WoDeHKViewHolder;

public class WoDeHKActivity extends ZjbBaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private EasyRecyclerView recyclerView;
    private RecyclerArrayAdapter<AppECard> adapter;
    private int page = 0;
    private TextView textViewRight;
    private boolean isGuanLi = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wo_de_hk);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {
        recyclerView = (EasyRecyclerView) findViewById(R.id.recyclerView);
        textViewRight = (TextView) findViewById(R.id.textViewRight);
    }

    @Override
    protected void initViews() {
        ((TextView) findViewById(R.id.textViewTitle)).setText("我的贺卡");
        textViewRight.setText("管理");
        initRecycle();
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageBack).setOnClickListener(this);
        textViewRight.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        onRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textViewRight:
                isGuanLi = !isGuanLi;
                List<AppECard> allData = adapter.getAllData();
                for (int i = 0; i < allData.size(); i++) {
                    allData.get(i).setGuanLi(isGuanLi);
                }
                adapter.notifyDataSetChanged();
                break;
            case R.id.imageBack:
                finish();
                break;
        }
    }

    private void initRecycle() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        SpaceDecoration itemDecoration = new SpaceDecoration((int) DpUtils.convertDpToPixel(1, WoDeHKActivity.this));
        itemDecoration.setPaddingEdgeSide(true);
        itemDecoration.setPaddingStart(true);
        recyclerView.addItemDecoration(itemDecoration);
        int red = getResources().getColor(R.color.basic_color);
        recyclerView.setRefreshingColor(red);
        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<AppECard>(WoDeHKActivity.this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                int layout = R.layout.item_wode_qingjian;
                return new WoDeHKViewHolder(parent, layout);
            }

        });
        adapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnMoreListener() {
            @Override
            public void onMoreShow() {
                OkObject okObject = getOkObject();
                OkGo.post(okObject.getUrl())//
                        .tag(this)//
                        .headers(okObject.getHeaders())
                        .upJson(okObject.getJson())//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                try {
                                    page++;
                                    AppECardPaging appECardPaging = GsonUtils.parseJSON(s, AppECardPaging.class);
                                    List<AppECard> appECardList = appECardPaging.getCards();
                                    for (int i = 0; i < appECardList.size(); i++) {
                                        appECardList.get(i).setGuanLi(isGuanLi);
                                    }
                                    adapter.addAll(appECardList);
                                } catch (Exception e) {
                                    adapter.pauseMore();
                                }
                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                super.onError(call, response, e);
                                if (response != null) {
                                    if (response.code() == 401) {
                                        showReLoginDialog();
                                    } else if (response.code() == 403) {
                                        showTipDialog("新版本");
                                    } else {
                                        adapter.pauseMore();
                                    }
                                } else {
                                    adapter.pauseMore();
                                }
                            }
                        });
            }

            @Override
            public void onMoreClick() {

            }
        });
        adapter.setNoMore(R.layout.view_nomore_qingjian);
        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });
        recyclerView.setRefreshListener(this);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent();
                intent.setClass(WoDeHKActivity.this, HeKaYLActivity.class);
                intent.putExtra(Constant.INTENT_KEY.URL, adapter.getItem(position).getPreview());
                intent.putExtra(Constant.INTENT_KEY.TITLE,"查看贺卡");
                startActivity(intent);
            }
        });
    }

    private OkObject getOkObject() {
        String url = Constant.HOST + Constant.Url.AppECardService + "query" + "?page=" + page + "&page_size=10" + "&sort_key=isAutoGeneration&desc=true";
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    @Override
    public void onRefresh() {
        isGuanLi = false;
        page = 0;
        OkObject okObject = getOkObject();
        OkGo.post(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .upJson(okObject.getJson())//
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.LogShitou("我的贺卡查询", s);
                        try {
                            page++;
                            AppECardPaging appECardPaging = GsonUtils.parseJSON(s, AppECardPaging.class);
                            List<AppECard> appECardList = appECardPaging.getCards();
                            for (int i = 0; i < appECardList.size(); i++) {
                                appECardList.get(i).setGuanLi(isGuanLi);
                            }
                            adapter.clear();
                            adapter.addAll(appECardList);
                        } catch (Exception e) {
                            showError(getResources().getString(R.string.shujuchucuo));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response != null) {
                            if (response.code() == 401) {
                                showError("Token失效");
                                showReLoginDialog();
                            } else if (response.code() == 403) {
                                showError("有新版本");
                            } else {
                                showError(getResources().getString(R.string.wangluochucuo));
                            }
                        } else {
                            showError(getResources().getString(R.string.wangluochucuo));
                        }
                    }

                    public void showError(String msg) {
                        View view_loaderror = LayoutInflater.from(WoDeHKActivity.this).inflate(R.layout.view_loaderror, null);
                        TextView textMsg = (TextView) view_loaderror.findViewById(R.id.textMsg);
                        textMsg.setText(msg);
                        view_loaderror.findViewById(R.id.buttonReLoad).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                initData();
                            }
                        });
                        recyclerView.setErrorView(view_loaderror);
                        recyclerView.showError();
                    }
                });
    }
}
